package com.scholar.goods.exception;

import com.scholar.shop.common.BusinessException;
import com.scholar.shop.common.CommonError;
import com.scholar.shop.common.CommonRes;
import com.scholar.shop.common.EmBusinessError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 利用aop 进行统一异常处理
 * 表示 所有的controller的异常都会被该切面拦截
 * @author kimmy
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public static final String AUTH_NULL_MESSAGE = "value for name Authorization == null";

    /**
     * 处理异常
     * @param request  请求
     * @param response 响应
     * @param e 异常对象信息
     * @return 校验结果
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes<Object> doError(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        if (e instanceof BusinessException) {
            CommonError commonError = ((BusinessException) e).getCommonError();
            log.error("发生业务异常，异常编码为 {}, 异常信息为 {}", commonError.getErrCode(), commonError.getErrMsg(), e);
            return CommonRes.fail(((BusinessException)e).getCommonError());
        } else if (AUTH_NULL_MESSAGE.equals(e.getMessage())) {
            CommonError commonError = new CommonError(EmBusinessError.USER_SERVICE_SESSION_TIME_OUT);
            return CommonRes.fail(commonError);
        } else if (e instanceof NoHandlerFoundException) {
            return CommonRes.fail(new CommonError(EmBusinessError.SYS_NO_HANDLER_FOUND));
        } else if (e instanceof MissingServletRequestParameterException) {
            return CommonRes.fail(new CommonError(EmBusinessError.SYS_REQUEST_PARAMETER_ERROR));
        } else if (e instanceof MethodArgumentTypeMismatchException) {
            return CommonRes.fail(new CommonError(EmBusinessError.SYS_REQUEST_PARAMETER_TYPE_NOT_MATCH_ERROR));
        } else if (e instanceof org.springframework.web.client.ResourceAccessException) {
            return CommonRes.fail(new CommonError(10008, "访问超时请重试"));
        } else {
            return CommonRes.fail(new CommonError(EmBusinessError.SYS_UNKNOWN_ERROR));
        }
    }

}